<?php

namespace App\Service\Common;

use Illuminate\Support\Facades\File;
use Kuafu\File\FileUtil;
use OSS\Core\OssException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class FileService
{
    /**
     * 转存阿里云oss
     *
     * @param string $originalFile
     * @param string $ossFile
     * @param string $modulePath
     * @return mixed
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws OssException
     * @throws \Exception
     */
    public static function transferred(string $originalFile, string $ossFile, string $modulePath = "common")
    {
        try {
            $fileSystem = getFileSystem();
            $localDir   = getTmpDir("/{$modulePath}/" . formatDateYmd(time()));
            if (!$fileSystem->isDirectory($localDir)) {
                $fileSystem->makeDirectory($localDir, 0777, true);
            }
            $suffix    = explode("?", File::extension($originalFile))[0];
            $localFile = vsprintf("{$localDir}/%s.%s", [
                md5($originalFile),
                $suffix
            ]);
            $fileSystem->put($localFile, file_get_contents($originalFile));

            $sha256  = hash_file('sha256', $localFile);
            $ossInfo = FileUtil::uploadFile(
                $localFile,
                $suffix,
                vsprintf("%s/%s/%s/%s", [
                    $modulePath,
                    substr($sha256, 0, 2),
                    substr($sha256, 2, 2),
                    $ossFile
                ])
            );
            $fileSystem->delete($localFile);
            return $ossInfo["url"];
        } catch (\Exception $exception) {
            logException("文件转存失败", $exception);
            throw $exception;
        }
    }


}
